﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using Ionic.Zip;

namespace XDA_ROM_Hub
{
    public partial class ProgressAddon : Form
    {
        private string FullRomPath = Properties.Settings.Default.RomPath + @"\" + Properties.Settings.Default.RomFileName;
        private Thread thrDownload;
        private Stream strResponse;
        private Stream strLocal;
        private HttpWebRequest webRequest;
        private HttpWebResponse webResponse;
        private static int PercentProgress;
        private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);
        bool goPause = false;

        public ProgressAddon()
        {
            InitializeComponent();
            UserClosing = false;
            //this.buttonExit.Click += new EventHandler(buttonExit_Click);
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);

            if (File.Exists(FullRomPath))
            {
                lblProgress.Text = "Already downloaded.";
                this.Hide();
                if (Properties.Settings.Default.IsBootAnimation == true)
                {
                    DSE dse = new DSE();
                    dse.boot_animation_flasher();
                }
            }
        }

        private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
        {
            PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
            prgDownload.Value = PercentProgress;
            lblProgress.Text = "Downloaded " + BytesRead / 1048576 + "MB out of " + TotalBytes / 1048576 + "MB (" + PercentProgress + "%)";
            if (PercentProgress == 100)
            {
                this.Hide();
                if (Properties.Settings.Default.IsBootAnimation == true)
                {
                    DSE dse = new DSE();
                    dse.boot_animation_flasher();
                }
            }
            else
            {

            }
        }

        private void Download(object startPoint)
        {

            try
            {
                int startPointInt = Convert.ToInt32(startPoint);
                
                    webRequest = (HttpWebRequest)WebRequest.Create(Properties.Settings.Default.AddonURL);



                    try
                    {
                        webRequest.AddRange(startPointInt);

                        webRequest.Credentials = CredentialCache.DefaultCredentials;
                        webResponse = (HttpWebResponse)webRequest.GetResponse();
                        
                    }
                    catch
                    {
                        this.TopMost = false;
                        MessageBox.Show("This addon could not be found, Please report the error on www.sf.net/p/xperiaromhub.", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        try
                        {
                            strResponse.Close();
                            strLocal.Close();
                        }
                        catch { }
                    }
Int64 fileSize = webResponse.ContentLength;
                strResponse = webResponse.GetResponseStream();

                if (startPointInt == 0)
                {
                    strLocal = new FileStream(FullRomPath, FileMode.Create, FileAccess.Write, FileShare.None);
                }
                else
                {
                    strLocal = new FileStream(FullRomPath, FileMode.Append, FileAccess.Write, FileShare.None);
                }

                int bytesSize = 0;
                byte[] downBuffer = new byte[2048];

                while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    strLocal.Write(downBuffer, 0, bytesSize);
                    this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize + startPointInt });

                    if (goPause == true)
                    {
                        break;
                    }
                }
            }
            finally
            {
                strResponse.Close();
                strLocal.Close();
            }
        }




        private void Progress_Load(object sender, EventArgs e)
        {
            if (thrDownload != null && thrDownload.ThreadState == ThreadState.Running)
            {
                MessageBox.Show("A download is already running. Please either the stop the current download or await for its completion before starting a new one.", "Download in progress", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                lblProgress.Text = "Download Starting";
                thrDownload = new Thread(new ParameterizedThreadStart(Download));
                thrDownload.Start(0);
            }
        }

        public bool UserClosing { get; set; }

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                thrDownload.Abort();
                webResponse.Close();
                strResponse.Close();
                strLocal.Close();
                prgDownload.Value = 0;
                lblProgress.Text = "Download Stopped";
                this.Hide();
            }
            catch { MessageBox.Show("e"); }


        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            thrDownload.Abort();
            webResponse.Close();
            strResponse.Close();
            strLocal.Close();
            prgDownload.Value = 0;
            lblProgress.Text = "Download Stopped";
        }

    }

}

